from django.views import View
from django_redis import get_redis_connection
from django import http

from .image_code import createImageCode
from celery_tasks.sms.smsCode.mobileCode import send_message
from celery_tasks.sms.tasks import send_sms_code

import logging

# 创建日志输出器
logger = logging.getLogger('collect')

# Create your views here.


class ImageCodeView(View):
    """图片验证码模块"""
    def get(self, request, uuid):
        """
        :param request:
        :param uuid:   通用唯一识别码，用于识别该图形验证码是属于哪个用户的
        :return:  image/jpg
        """
        # 生成图片验证码
        text, image = createImageCode()
        print(text)
        # 把图片转为二进制响应给浏览器
        imagepath = r'D:\project\mido-mall\meiduo_mall\meiduo_mall\static\images\veri_code.jpg'
        image_data = open(imagepath, "rb").read()
        # print(image_data)

        # 保存图形验证码 redis
        redis_conn = get_redis_connection('image_code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应图形验证码  http.HttpResponse('响应体', '数据类型')
        return http.HttpResponse(image_data, content_type='image/jpg')


class SMSCodeView(View):
    """短信验证码"""
    def get(self, request, mobile):
        """
        :param request:
        :param mobile:   手机号
        :return:   JSON
        """
        # 接收参数（手机号，uuid，图形验证码）
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验参数
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden('缺少必传的参数')

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('image_code')

        # 判断用户是否频繁发送短信验证码
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({
                'code': '4002',
                'errmsg': '发送短信验证码过于频繁'
            })

        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({
                'code': '4001',
                'errmsg': '图形验证码已失效'
            })
        # 删除图形验证码
        redis_conn.delete('img_%s' % uuid)
        print(image_code_server)
        print(image_code_client)
        # 对比图形验证码
        # 验证码转小写
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({
                'code': '4001',
                'errmsg': '输入图形验证码有误'
            })

        # 生成短信验证码
        import random
        random_code = random.randint(100000, 999999)
        logger.info(random_code)  # 手动输出日志
        print(random_code)

        """
        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, 300, random_code)
        # 保存发送短信验证码的标志
        redis_conn.setex("send_flag_%s" % mobile, 60, 1)
        """

        """使用pipeline管理redis"""
        # 创建redis管道
        pipeline = redis_conn.pipeline()
        # 将命令添加到队列中
        # 保存短信验证码
        pipeline.setex('sms_%s' % mobile, 300, random_code)
        # 保存发送短信验证码的标志
        pipeline.setex("send_flag_%s" % mobile, 60, 1)
        # 执行
        pipeline.execute()

        # 发送短信验证码
        # result = send_message(mobile, random_code)

        # 使用celery发送短信
        result = send_sms_code.delay(mobile, random_code)   # 不要忘记写delay

        # 响应结果
        if result:
            return http.JsonResponse({
                'code': '0',
                'errmsg': '发送短信成功'
            })

